use strict;
use warnings;

use WSePagesImport;
use Data::Dumper;
use DE_EPAGES::Core::API::Script qw( RunScript );
use DE_EPAGES::Core::API::Error qw( Error ExistsError GetError );
use DE_EPAGES::Database::API::Connection qw( RunOnStore );
use DE_EPAGES::Presentation::API::PageCache qw (InvalidatePageCache);
use DE_EPAGES::WebInterface::API::MessageCenter qw( SynchronizeCache );
use Getopt::Long;

my $DEBUG;
my $debugf = GetOptions( "debug" => \$DEBUG );

my %Author = (
    'Username' => 'XXXXXXXXXXXtest',
    'Password' => 'xXXXXXXXXXXXU2',
);

my %ProductSearchRequest = (
    'PriceTo'        => 0,
    'PriceFrom'      => 0,
    'SourceKey'      => 'WEB1BIB',
    'CustomerType'   => '',
    'CustomerNumber' => 0,
    'CurrencyCode'   => 'GBP',

    'IncludeDiscounts'       => 'true',
    'IncludeFreeStock'       => 'true',
    'IncludePrices'          => 'true',
    'IncludePurchases'       => 'true',
    'IncludeComponents'      => 'true',
    'IncludePromotions'      => 'true',
    'IncludeDocuments'       => 'true',
    'IncludeCategories'      => 'true',
    'IncludeSalesOrderLines' => 'true',
    'IncludeSellingCodes'    => 'true',
    'SortBy'                 => 'ProductCode',
    'SortOrder'              => 'ASC',
    'Page'                   => 1,
    'RecordsPerPage'         => 20,
    'SearchValue'            => 'Oscar Wilde',
    'SearchBy'               => 'All',
    'Warehouse'              => '',
    'Category'               => '',
);

#Value "Page" will be overriden later by hitMe(x) method -where 'x' is a page number

my %FieldsAssignment = (

    'Name'              => 'ProductDescription',
    'Price'             => 'DiscountPrice',
    'StockLevel'        => 'Stock:TrueFreeStock',
    'ManufacturerPrice' => 'RRP',
    'Alias'             => 'ProductCode',
    'Description'       => 'TechnicalText',
    'Author'            => 'BookDetails:Author',
    'ManufacturerSKU'   => 'BookDetails:AlternativeRef',
    'ProductFormat'     => 'BookDetails:Format',
    'ISBN'              => 'BookDetails:ISBN',
    'Category6'         => 'BookDetails:MajorCategory',
    'Manufacturer'      => 'BookDetails:Publisher',
    'Category1'         => 'BookDetails:SubCategory1',
    'Category2'         => 'BookDetails:SubCategory2',
    'Category3'         => 'BookDetails:SubCategory3',
    'Category4'         => 'BookDetails:SubCategory4',
    'Category5'         => 'BookDetails:SubCategory5',
);

#Define list of categories we will be using to import, refer %FieldsAssignment var.
my @categoriesArr = (
    'Category6', 'Category1', 'Category2', 'Category3',
    'Category4', 'Category5'
);

sub Main {

    local $| = 1;

    my $Password   = "XXXXXXXXXXX";
    my $StoreName1 = "Store";

    RunOnStore(
        Store      => $StoreName1,
        DBPassword => $Password,
        Sub        => sub {
            my $start_run = time();
# Please note all errors and detailed infos are in log file you can track it on the other console window "tail -f"
#Log4perl is used - please refer doc and make all changes necessary in the config.
#WSePagesImport->new parameters:
#default SearchRequest hash reference
#Authorization hash reference
#FieldsAssignment - hash reference
#shop path,
#import mode(update - will update all attributes but not master product number will delete products not present during import)
#                    (add  - will skip all masters which are already in db will not delete anything)
# verbose display result on the stdout console - quiet -will do the opposite.
# debug - last marameter - 0 - 1 - display webservice debug

            my $epLink = WSePagesImport->new(
                \%ProductSearchRequest, \%Author,
                \%FieldsAssignment,     \@categoriesArr,
                "/Shops/Bibliophile",   "update",
                "verbose",              $DEBUG
            );
            $epLink->{timeFlag} = time();
            $epLink->LogInfo(
                "Preparing to start the import. Initiate ePages config elements."
            );

            if ( $epLink->{_import_mode} eq "update" ) {
                $epLink->generateePagesBooksList();
            }

            $epLink->generateCategoriesList();

            $epLink->LogInfo("Start the proper import. First connection.");

# Define list of categories we will be using to import refer %FieldsAssignment var.
# my @categoriesArr = ('Category1', 'Category2', 'Category3', 'Category4', 'Category5');
# $epLink->{categoriesList} = \@categoriesArr;

            # $epLink->ChangeRequestParameters('PriceTo' 								=> 100,
            #																	'PriceFrom' 							=> 5,
            #																	);
            # This is the way you can override the request:
            my $NewPrices = {
                'PriceTo'     => 0,
                'PriceFrom'   => 0,
                'SearchValue' => '',

                #   'SearchValue' 						=> '64171',
                #   'SearchBy' 							=> 'ProductCode',
            };
            $epLink->ChangeRequestParameters($NewPrices);

# hitMe as a parameter can have page number - this will be helpful when final import starts.
            my $loop        = 1;
            my $currentpage = 1;
            while ($loop) {
                $epLink->LogInfo( "Importing page: " . $currentpage );
                $epLink->{currentpage} = $currentpage;
                my $arrRespond       = $epLink->hitMe($currentpage);
                my $imported_records = $epLink->importProducts($arrRespond);
                if ( $imported_records
                    == $ProductSearchRequest{'RecordsPerPage'} )
                {
                    $currentpage++;
                }
                else {
                    $loop = 0;
                }
            }

            if ( $epLink->{_import_mode} eq "update" ) {
                $epLink->removeOldePagesBooks();
            }

            my $end_run  = time();
            my $run_time = $end_run - $start_run;
            $epLink->LogInfo(
                "Job took overall: " . $run_time . " seconds." );
            if ( $epLink->{_display} eq "verbose" ) {
                print "Job took $run_time seconds.\n";
            }

            $epLink->LogInfo(
                "Deleted books:\n" . Dumper( $epLink->{ePagesBooksList} ) );
            $epLink->LogInfo( "Categories pulled off Options:\n"
                    . Dumper( $epLink->{categories} ) );
            $epLink->LogInfo( "These categories do not exist in ePages:\n"
                    . Dumper( $epLink->{nonExistentCategories} ) );
            print Dumper( $epLink->{emptyFields} );

            my $title   = 'Product import finished';
            my $to      = 'accounts@XXXXXXXXXXXks.com';
            my $from    = 'store@XXXXXXXXXXXks.com';
            my $subject = 'Product import finished';

            open( MAIL, "|/usr/sbin/sendmail -t" );
## Mail Header
            print MAIL "To: $to\n";
            print MAIL "From: $from\n";
            print MAIL "Subject: $subject\n\n";
## Mail Body
            print MAIL "Product import has been just finished successfully\n";
            close(MAIL);

        },
    );

    eval { SynchronizeCache(); };
    Warning( GetError() ) if ExistsError();
    return;
}

RunScript( 'Sub' => \&Main );
